import logging
import random

import requests

import login.selenium_login_off as slo
from utils import tools as ts

# 获取日志器
# setup_logging()
logger = logging.getLogger("net_login")

count = 0


def net_get_request():
    config_params = ts.read_json_file()
    url = config_params.get("url")
    params = config_params.get("params")
    headers = config_params.get("headers")
    params["lang"] = "zh"
    params["v4ip"] = ts.get_local_ip()
    params["v"] = f"dr{random.randint(100, 9999)}"  # 回调函数名随机化

    try:
        response = requests.get(url, params=params, headers=headers)
        if response.status_code != 200:
            raise Exception("请求错误")
        logger.info("GET 请求成功！响应状态码: {}".format(response.status_code))
        result = ts.parse_jsonp_response(response.content)
        logger.info(result)
        if result.get("result") == 1:
            logger.info("登录成功！")
            return True
        else:
            logger.error(f"登录失败：{result.get('msga')}，尝试自动注销账号并重新登录")
            dr_url = config_params.get("dr_url")
            dr_username = config_params.get("dr_username")
            dr_password = config_params.get("dr_password")
            dr_username_field = config_params.get("dr_username_field")
            dr_password_field = config_params.get("dr_password_field")
            dr_login_button_xpath = config_params.get("dr_login_button_xpath")
            dr_exit_button_xpath = config_params.get("dr_exit_button_xpath")
            slo.auto_login(url=dr_url, username=dr_username, password=dr_password,
                           username_field_id=dr_username_field, password_field_id=dr_password_field,
                           login_button_xpath=dr_login_button_xpath, exit_button_xpath=dr_exit_button_xpath)
            global count
            # 限制次数重新登录次数不超过三次
            if count == 3:
                return False
            net_get_request()
    except requests.exceptions.RequestException as err:
        logger.error(f"请求错误: {err}")


if __name__ == '__main__':
    net_get_request()
